<template>
	<view class="bg-light" style="padding-bottom: 110rpx;" id="list">

		<view v-if="screenWidth<480" class="flex-shrink" style="height:100rpx;"></view>
		<view v-if="screenWidth<480" class="fixed-top w-100 xpy flex align-end justify-center bg-light"
			style="height: 100rpx;">
			<uni-icons v-if="gi>1&&!isSubmit" @click="handleBack()" type="left"
				style="position: absolute;left: 20rpx; bottom: 20rpx;" size="25"></uni-icons>
			<uni-icons v-if="isSubmit" @click="handleSubmit()" type="left"
				style="position: absolute;left: 20rpx; bottom: 20rpx;" size="25"></uni-icons>
			<text class="font pb-2">礼品卡领取</text>
		</view>
		<!-- <view v-else class="fixed-top flex" style="height: 100rpx;" :style="{backgroundColor: tabBar.backgroundColor}">
				<view class="xpy flex align-center font text-success">
					<text v-if="!isLogin" class="mr-5" @click="handleLogin">请登录</text>
					<text v-if="!isLogin" @click="handleZHUCE">免费注册</text>
					<text v-if="isLogin" class="mr-5">欢迎！*</text>
					<text v-if="isLogin" @click="handleExit">退出</text>
				</view>
			</view> -->
		<!-- 自提选项 -->
		<view v-if="customerAddress" class=" ml-2 p my-2 rounded-circle flex" style="width: 320rpx;">
			<view @click="handleMode" class="px-3 py-1 rounded-circle flex align-center"
				:class="!isSelfPickup?'bg-success':''" style="width: 100rpx;">
				<text class="font-sm" :class="!isSelfPickup?'text-white':'text-success'">商家配送</text>
			</view>
			<!-- 			<view @click="handleMode" class="px-3 py-1 rounded-circle flex align-center"
				:class="isSelfPickup?'bg-success':''" style="width: 100rpx;">
				<text class="font-sm" :class="isSelfPickup?'text-white':'text-success'">到店自提</text>
			</view> -->
		</view>
		<!-- 地址选择 -->
		<view v-if="!isSelfPickup" class="m-2 bg-white rounded-lg text-dark">
			<!-- 已选中地址 -->
			<view v-if="customerAddress" @click="handleAddress()" class="ml-2 py-2 flex justify-between align-center">
				<view class="flex flex-column">
					<text class="font">{{customerAddress.Address.replaceAll('/','')}}</text>
					<text class="font-md my-2 font-weight-bold">{{customerAddress.Address_Details}}</text>
					<text class="font">{{customerAddress.Name}} {{customerAddress.Phone}}</text>
				</view>
				<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
			</view>
			<!-- 未选中地址 -->
			<view v-else @click="handleAddress()" class="ml-2 py-2 flex justify-between align-center">
				<view class="flex flex-column">
					<text class="font">暂未获取到收货地址</text>
					<text class="font-lg my-2 font-weight-bold">请新建收货地址</text>
					<text class="font"></text>
				</view>
				<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
			</view>
			<!-- 配送方式 -->
			<view @click="handleDelivery()" class="flex py-2 align-center justify-between">
				<text class="ml-2 font">配送方式</text>
				<view>
					<text class="mr-2 font">快递 免运费</text>
					<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
				</view>
			</view>
		</view>
		<!-- 提货选择 -->
		<view v-else class="m-2 bg-white rounded-lg text-dark">
			<!-- 已选择提货人 -->
			<view class="ml-2 py-2 flex justify-between align-center">
				<view class="flex flex-column w-100">
					<text class="font-md font-weight-bold">鲜鸡蛋提货点</text>
					<text class="font my-2">黑龙江省哈尔滨市香坊区木材东街河畔花园</text>
					<view @click="handlePickupPerson()" class="mt-2 flex justify-between">
						<text class="font">提货人</text>
						<view v-if="defaultPerson">
							<text class="font font-weight-bold">{{defaultPerson.Name}} {{defaultPerson.Phone}}</text>
							<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
						</view>
						<view v-else>
							<text class="font font-weight-bold">去创建提货人信息</text>
							<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
						</view>
					</view>
				</view>
			</view>
			<!-- 提货时间 -->
			<!-- 未做 -->
			<!-- <view class="flex py-2 align-center justify-between">
				<text class="ml-2 font">提货时间</text>
				<view>
					<text class="mr-2 font text-success">请选择提货时间</text>
					<uni-icons type="right" class="mr-2" color="#828d96" size="16"></uni-icons>
				</view>
			</view> -->
		</view>
		<!-- 商品信息 -->
		<view class="" id="list">
			<view v-for="(item,index) in goods" :key="index" class=" m-2 bg-white py-2 rounded-lg mb-2">
				<view class="flex">
					<view class="flex-shrink rounded overflow-hidden"
						style="position: relative; width: 180rpx; height: 180rpx;">
						<image :src="Domain_IMG+item.Picture_URL" class="img" mode="aspectFit"></image>
						<view v-if="isStock.some(i=>i==item.Article_SerialNumber)" class="border border-danger"
							style="position: absolute; bottom: 60rpx; left: 20rpx;transform:rotate(-45deg);">
							<text class="text-danger fout">库存不足</text>
						</view>
					</view>
					<view class="ml-2 flex flex-column justify-between w-100 pr-2">
						<view class="getvalue" :data-name="item.Article_Name">{{item.Article_Name}}</view>
						<view class="mr-2 font-sm rounded-lg flex justify-center align-center"
							style="background-color: rgb(247,248,250);width: 80rpx;height: 40rpx;"
							v-if="item.Specifications_Name">
							{{item.Specifications_Name}}
						</view>
						<view class="flex justify-between">
							<money class="money1" :data-Amount="item.Amount" :money="item.Amount.toString()"></money>
							<text class="text-muted font-sm gdQuantity"
								:data-Quantity="item.Quantity">x{{item.Quantity}}</text>

							<text class="font-sm" style="color: green;">实付:0元</text>
						</view>
					</view>
					<!-- 	<view class="" @click="selectGoodsClick">
						<button>选择</button>
						<button>取消</button>
					</view> -->
				</view>
			</view>
		</view>
		<!-- 总计 -->
		<view class="m-2 py-2 bg-white rounded-lg">
			<view class="mx-2 flex flex-column">
				<!-- 商品总价 -->
				<view class="flex mb-2 justify-between">
					<view><!-- 左 -->
						<text class="font text-dark">商品总价</text>
						<text class="ml-1 font text-muted">共{{goods.length}}件商品</text>
					</view>
					<view><!-- 右 -->
						<!-- 商品总价 -->
						<text class="font text-dark font-weight-bold"></text>
					</view>
				</view>
				<!-- 合计 -->
				<view class="flex mt-2 justify-end">
					<view>
						<text class="font text-dark">合计：</text>
						<text class="ml-1  text-dark">0元</text>
					</view>
				</view>
			</view>
		</view>
		<!-- 支付方式 -->
		<!-- <view v-for="(item,index) in pay" :key="index" @click="handlePay(item)"
			class="mx-2 py-2 bg-white rounded-lg flex justify-between">
			<view class="ml-2 flex align-center">
				<uni-icons fontFamily="iconfont" :color="item.Color" size="20">{{item.Icon}}</uni-icons>
				<text class="font ml-2 text-dark">{{item.Name}}</text>
			</view>
			<view class="mr-2">
				<uni-icons v-if="!item.isSelect" type="circle" :color="item.Color" size="20"></uni-icons>
				<uni-icons v-else type="checkbox-filled" :color="item.Color" size="20"></uni-icons>
			</view>
		</view>
		<picker v-if="selectedPay =='储值支付'" @change="PickerChange" class="font" :range="card" range-key="Name">
			<view v-if="prepayment_card" class="flex flex-column ml-2 bg-white m-2 text-center p-2">
				<text class="font ">卡号:{{prepayment_card.Prepayment_Card_Scheme_Name}}</text>
				<text class="font my-2">卡名：{{prepayment_card.Prepayment_Card_SerialNumber}}</text>
				<text class="font ">剩余金额：{{prepayment_card.Amount}}元</text>
			</view>
			<view v-else class="w-100 flex justify-center">
				<text class="font font-weight-bold mt-3">请选择储值卡</text>
			</view>
		</picker> -->
		<!-- 买家留言 -->
		<view class="m-2 py-2 bg-white flex rounded-lg">
			<text class="ml-2 font flex-shrink pr-4">买家留言</text>
			<textarea class="font text-right w-100 mr-2" placeholder-class="text-muted text-right"
				placeholder="留言建议提前协商 (250字以内)" auto-height :value="message"></textarea>
		</view>
		<!-- 底部提交 -->
		<view class="fixed-bottom xpy shadow flex align-center justify-between bg-white" style="height: 110rpx;">
			<view class="ml-3 flex align-end">
				<text class="font-lg">应付：</text>
				<money :money="0"></money>
			</view>
			<view class="mr-3 bg-white px-3 py-2 rounded-circle flex align-center">
				<view @click="wxPayfor()" :style="{backgroundColor:pay.filter(i=>i.isSelect)[0].Color}"
					class="ml-2 px-4 py-2 flex align-center rounded-circle">
					<text class="text-white font">立即领取</text>
				</view>
			</view>
		</view>
		<!-- 地址弹窗 -->
		<popUp :show="isAddress" @scrollTolower="onAddressScollBottom" title="请选择收获地址" :button="['新增地址']" Height="50"
			@Close="handleAddress" @submit1="handleAddressAdd">
			<view class="mx-2 py-2">
				<!-- 地址详情 -->
				<view v-for="(item,index) in tableDataAddress" :key="index"
					class="bg-white mb-2 py-2 w-100 flex align-center rounded-lg">
					<!-- 信息 -->
					<view class="flex w-100 align-center" @click="selectAddress(item)">
						<view class="flex-shrink mx-2">
							<uni-icons
								v-if="item.Address_SerialNumber!=(customerAddress==null?'':customerAddress.Address_SerialNumber)"
								type="circle" color="#28a745" size="20"></uni-icons>
							<uni-icons v-else type="checkbox-filled" color="#28a745" size="20"></uni-icons>
						</view>
						<view class="w-100 flex flex-column">
							<text class="font text-dark">{{Address(item.Address,item.Address_Details)}}</text>
							<text class="font mt-2 text-muted">{{item.Name}} {{item.Phone}}</text>
						</view>
					</view>
					<!-- 修改 -->
					<view @click="handleAddressEdit(item.Address_SerialNumber)" class="flex-shrink mr-2">
						<uni-icons fontFamily="iconfont" color="#828d96" size="20">{{'\ue8cf'}}</uni-icons>
					</view>
				</view>
			</view>
		</popUp>
		<!-- 提货人 -->
		<popUp :show="isPickupPerson" @scrollTolower="onPickupScollBottom" title="请选提货人" @submit1="pickupPersonAdd"
			:button="['新增提货人']" Height="50" @Close="handlePickupPerson">
			<view class="pt-2 bg-white flex flex-column" v-for="(item,index) in tableDataPickup" :key="index">
				<view class="pb-2 flex justify-between align-center" @click="selectpickupPerson(item)">
					<view class="flex ml-4">
						<uni-icons @click.stop="pickupPersonEdit(item.Picker_SerialNumber)" fontFamily="iconfont"
							color="#828d96" size="20">{{'\ue8cf'}}</uni-icons>
						<text class="font ml-2">{{item.Name}}，{{item.Phone}}</text>
					</view>
					<view class="flex-shrink mr-4">
						<uni-icons v-if="item.Picker_SerialNumber!=defaultPerson.Picker_SerialNumber" type="circle"
							color="#28a745" size="20"></uni-icons>
						<uni-icons v-else type="checkbox-filled" color="#28a745" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</popUp>
		<!-- 配送方式 -->
		<popUp :show="isDelivery" title="请选择配送方式" Height="40" @Close="handleDelivery">
			<view class="pt-2 bg-white flex flex-column">
				<view class="pb-2 flex justify-between align-center">
					<text class="font ml-4">同城配送</text>
					<view class="flex-shrink mr-4">
						<uni-icons v-if="false" type="circle" color="#28a745" size="20"></uni-icons>
						<uni-icons v-else type="checkbox-filled" color="#28a745" size="20"></uni-icons>
					</view>
				</view>
				<view class="pb-2 flex justify-between align-center">
					<text class="font ml-4">快递 免运费</text>
					<view class="flex-shrink mr-4">
						<uni-icons v-if="false" type="circle" color="#28a745" size="20"></uni-icons>
						<uni-icons v-else type="checkbox-filled" color="#28a745" size="20"></uni-icons>
					</view>
				</view>
			</view>
		</popUp>
		<!-- 优惠券 -->
		<popUp :show="isCoupon" title="请选择优惠券" @submit1="bsyClick()" @submit2="makeSure()" :button="['不使用优惠券','确认']"
			Height="70" @Close="handleCoupon">
			<view class="py-2 bg-white flex flex-column">
				<!-- 导航栏 -->
				<view class="bg-white flex align-center">
					<!-- 搜索框 -->
					<view class="w-100 mx-4 py-1 rounded-circle bg-light flex justify-between align-center">
						<input class="mx-2 font-sm w-100" type="text" placeholder-class="text-muted font-sm"
							placeholder="请输入优惠码" />
					</view>
					<!-- 兑换 -->
					<text class="pr-4 flex-shrink font text-success">兑换</text>
				</view>
				<!-- 选项卡 -->
				<view class="">
					<view v-for="(item,index) in coupon" :key="index">
						<view class="row flex justify-center align-center pb-1">
							<uni-icons @click="checkboxAddr(index)" :type="item.checked" color="#28a745"
								size="35"></uni-icons>
							<!-- <uni-icons @click="checkboxAddr(index)" type="checkbox-filled" color="#28a745"
								size="35"></uni-icons> -->
							<coupon :couponName="item.Coupon_Scheme_Name" :couponRule="item.Coupon_Scheme_Rule"
								:Min_Amount="item.Min_Amount" :Preferential="item.Preferential"></coupon>
						</view>
					</view>

				</view>
			</view>
		</popUp>
		<!-- 付款二维码 -->
		<view class="zfAlert" v-if="dislogPayCode">
			<view class="flex justify-center">
				<Qrcode ref="qrcode" onval :val="codeurl" :size="300" :load-make="true" :show-loading="false" />
				<!-- <uqrcode ref="uqrcode" canvas-id="qrcode" :value="codeurl" :options="{ margin: 10 }">
				</uqrcode> -->
			</view>
			<view class="flex justify-center">
				<button @click="back()">返回上一页</button>
				<button :loading="loading" @click="CompletePayfor()">支付完成后点击此处</button>
			</view>
		</view>
		<!-- 输入礼品卡密码 -->
		<view class="zfAlert" v-if="postcardStatus">
			<view class="" style="background-color: #fafafa;padding: 120rpx;border-radius: 15px;">
				<view class="flex justify-center" style="font-size:36rpx;">
					请输入礼品卡密码
				</view>
				<view class="code flex align-center justify-center" style="margin-top: 10vh;">
					<view class="flex align-center justify-center">
						<view v-for="(item, index) in 6" :key="index">{{ postcardPassword[index] && '●' || '' }}</view>
					</view>
				</view>
				<view class="keyboard flex flex-wrap">
					<button v-for="(item, index) in 9" :key="index" @click="key(index + 1)">
						<text>{{ index + 1 }}</text>
					</button>
					<button class="hide"></button>
					<button @click="key(0)">
						<text>0</text>
					</button>
					<button @click="del()">
						<uni-icons type="closeempty" size="30"></uni-icons>
					</button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	const app = getApp();
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import money from "@/components/tool/money.vue";
	import popUp from "@/components/tabs/pop-up.vue";
	import coupon from "@/components/tool/coupon.vue"
	import Qrcode from "@/components/qrcode/qrcode.vue"
	import WebSocketIO from "@/static/js/WebSocket.js"
	import {
		GetChengXu,
		GetRedis,
		GetUrlLink,
		setAsynChronousAdd,
		getGiftCardInfo
	} from "@/api/global.js"
	import {
		getPickerAllAction,
		getAddressAllAction
	} from "@/api/delivery.js"
	import {
		getSalesCouponAction
	} from "@/api/coupon.js"
	import {
		WeChatPayShopCarNative,
		CheckStock,
		WeChatDefray,
		addWeChatsetSalesOrderAction,
		salesOrderSaveAction,
		CollectionEdit
	} from "@/api/pay.js"
	import {
		accAdd,
		accSub,
		accMul,
		accDiv,
		addZero,
		validate,
		validatemobile,
		chooseLocation
	} from "@/static/js/GeneralUtil.js"
	import {
		NowTime
	} from "@/static/js/DateUtil.js"
	import {
		setSalesOrderAction,
		WXWeChatDefrayAction,
		getprepaymentCardSalesAction
	} from '@/api/WeChat.js'
	export default {
		components: {
			tabsTop, //顶部标题组件
			money, //钱样式
			popUp, //上移弹出啊
			coupon,
			Qrcode
		},
		data() {
			return {
				screenWidth:uni.getSystemInfoSync().windowWidth,
				Domain_IMG: app.globalData.Domain_IMG, //商品图片地址
				isSelfPickup: false, //到店自提
				//自提开始
				dislogPayCode: false, // 支付弹窗
				isPickupPerson: false, //提货人弹窗
				defaultPerson: null, //已选自提人
				tableDataPickup: [], // 存放自提人
				formPickup: { //自提人查询地址
					page: 1,
					limit: 10,
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
				},
				goods: [], // 商品信息
				totalPickup: 0, //自提人总数
				isReachPickup: true, //判断自提人是否查询完毕
				//配送开始
				isDelivery: false, //配送弹窗
				//优惠券开始
				isCoupon: false, //优惠券弹窗
				codeurl: '', //二维码
				//地址开始
				customerAddress: null, //已选地址
				isAddress: false, //地址弹窗
				formAddress: { //查询地址
					page: 1,
					limit: 10,
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
				},
				totalAddress: 0, //地址总数
				tableDataAddress: [], //存放地址
				isReachAddress: false, //判断地址是否查询完毕
				loading: false, //节流
				fixedCS: {
					page: 1,
					limit: 10,
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber
				},
				coupon: [], // 优惠券
				totalPrice: 0, // 总价
				preferential: 0, // 减免钱
				message: '', // 买家留言
				pay: [{
						Name: '微信支付',
						Icon: '\ue650',
						isSelect: true,
						Color: '#28a745'
					},
					{
						Name: '储值支付',
						Icon: '\ue695',
						isSelect: false,
						Color: '#ffc107'
					},
					// {
					// 	Name: '支付宝支付',
					// 	Icon: '\ue65f',
					// 	isSelect: false,
					// 	Color: '#007bff'
					// },
				],
				selectedPay: '',
				prepayment_card: null,
				card: [],
				first: true,
				RedisGoods: [],
				isStock: [], //判断是否售罄
				postcard_Sales_Order_SerialNumber: '', // 生成的订单号
				postcardPassword: '', // 礼品卡密码
				passwordStatus: true,
				passwordIcon: 'eye',
				postcardStatus: false, //控制礼品卡密码框显示
				postcardRule: '', // 礼品卡规则，可选择几种商品
				selectGoods: [], //  选择的商品
				Store_SerialNumber: '',
				Gift_Card_SerialNumber: '', //卡
				Collection_SerialNumber: '', //
			}
		},
		onLoad(e) {
			uni.showLoading({
				title: "加载中...",
			});
			const timer = setInterval(() => {
				if (app.globalData.Open_ID) {
					clearInterval(timer)
					uni.hideLoading()
					if (this.isAddress) { //地址查询
						this.formAddress.page = 1;
						this.getAddressAction(this.formAddress)
					}
					if (this.isPickupPerson) { //自提人查询
						this.formPickup.page = 1;
						this.getPickupPerson(this.formPickup)
					}
				}
			}, 50);
			if (e.hasOwnProperty('Gift_Card_SerialNumber')) {
				this.Gift_Card_SerialNumber = e.Gift_Card_SerialNumber
				this.getGiftCardInfo(e.Gift_Card_SerialNumber)
			} else {
				this.Gift_Card_SerialNumber = 'G000002500000091';
				this.getGiftCardInfo('G000002500000091')
				uni.showToast({
					title: '暂无该卡的信息',
					icon: 'error',
					duration: 2000
				})
			}
		},
		onShow() {
			//获取本地存储地址
			if (uni.getStorageSync("customerAddress")) {
				this.customerAddress = uni.getStorageSync("customerAddress")
			}
			if (uni.getStorageSync("defaultPerson")) {
				this.defaultPerson = uni.getStorageSync("defaultPerson")
			}
			if (this.isAddress) { //地址查询
				this.formAddress.page = 1;
				this.getAddressAction(this.formAddress)
			}
			if (this.isPickupPerson) { //自提人查询
				this.formPickup.page = 1;
				this.getPickupPerson(this.formPickup)
			}
		},
		computed: {
			Address() {
				return function(str1, str2) {
					try {
						return str1.replaceAll('/', '') + str2;
					} catch (e) {
						return "";
					}
				}
			},
			AccAdd(str1, str2) {
				return function(str1, str2) {
					try {
						return accAdd(str1, str2);
					} catch (e) {
						return "";
					}
				}
			},
			AccMul(str1, str2) {
				return function(str1, str2) {
					try {
						return accMul(str1, str2);
					} catch (e) {
						return "";
					}
				}
			},
			AccSub(str1, str2) {
				return function(str1, str2) {
					try {
						return accSub(str1, str2);
					} catch (e) {
						return "";
					}
				}
			},
			AccDiv(str1, str2) {
				return function(str1, str2) {
					try {
						return accDiv(str1, str2);
					} catch (e) {
						return "";
					}
				}
			},
		},
		methods: {
			// 输入密码保存起来
			key(key) {
				if (this.postcardPassword.length < 6) {
					this.postcardPassword += key
					if (this.postcardPassword.length === 6) {
						// 满六位调用兑换
						this.exchange();
					}
				}
			},
			del() {
				if (this.postcardPassword.length > 0) {
					this.postcardPassword = this.postcardPassword.substring(0, this.postcardPassword.length - 1)
				}
			},
			// 根据礼品卡流水号查询礼品卡的商品
			async getGiftCardInfo(Gift_Card_SerialNumber) {
				let res = await getGiftCardInfo({
					Gift_Card_SerialNumber,
					Open_ID: app.globalData.Open_ID
				});
				console.log(res, '123');
				if (res.status == 0) {
					this.goods = res.data.Article_Info
					this.Store_SerialNumber = res.data.gift_card_scheme.Children.gift_card_scheme_storescope[0]
						.Store_SerialNumber
					this.goods.forEach((item, index) => {
						this.totalPrice = accAdd(item.Amount, this.totalPrice)
					})
					console.log(this.goods);
				}
			},
			// 选中商品
			selectGoodsClick(good) {
				good.selectStatus = !good.selectStatus;
				if (good.selectStatus) {
					if (this.selectGoods.length < postcardRule) {
						this.selectGoods.push(good);
					} else {
						uni.showToast({
							title: '所选商品已达上限!',
							icon: "error",
							duration: 1000,
						})
					}
				} else {
					this.selectGoods.forEach((item, index) => {
						// 待修改
						// if ()
					})
				}
			},
			//  查询Redis中的商品
			async getRedisGoods(ID_Code_Key, callback) {
				let res = await GetRedis({
					Key: ID_Code_Key
				})
				if (res.Status == "success") {
					this.RedisGoods = JSON.parse(decodeURIComponent(res.Data))
					callback()
				}
			},
			handleMode() { //配送or自提
				this.isSelfPickup = !this.isSelfPickup
			},
			checkboxAddr(index) {
				// this.coupon[index].checked="circle-filled"
				if (this.coupon[index].checked == "circle-filled") {
					this.coupon[index].checked = "circle"; // 
				} else {
					this.coupon.forEach(item => {
						item.checked = "circle";
						this.$set(this.coupon, index, {
							...item,
							checked: "circle"
						})
					})
					this.coupon[index].checked = "circle-filled";
					let obj = this.coupon[index]
					this.$set(this.coupon, index, {
						...obj,
						checked: "circle-filled"
					})
				}
				if (this.coupon[index].checked == "circle-filled") {
					this.preferential = this.coupon[index].Preferential
				}
				var flag = true;
				this.coupon.forEach(item => {
					if (item.checked == "circle-filled") {
						flag = false;
					}
				})
				if (flag) {
					this.preferential = 0;
				}
			},
			makeSure() {
				var total = 0;
				this.goods.forEach((item, index) => {
					item.jm = parseInt(accMul(this.preferential, item.percentage) * 100) / 100;
					if (index < this.goods.length - 1) {
						total += item.jm;
					} else {
						item.jm = this.preferential - total;
					}
				})
				this.isCoupon = !this.isCoupon;
			},
			getData(e, callback) {
				var arr = [];
				this.goods.forEach(item => {
					arr.push(item.Article_SerialNumber)
				});
				this.fixedCS.Article_SerialNumber = JSON.stringify(arr);
				callback()
			},
			bsyClick() {
				this.preferential = 0;
				this.goods.forEach((item, index) => {
					item.jm = 0
				})
				this.coupon.forEach(item => {
					item.checked = "circle";
				})
				this.isCoupon = !this.isCoupon;
			},
			getvalues(selector) {
				const query = uni.createSelectorQuery().in(this);
				var ele = query.selectAll(selector);
				ele.fields({
					dataset: true,
					computedStyle: true,
					context: true
				}, function(e) { //   拿到节点中想要的键值对信息
					e.forEach(item => {})
				}).exec()
			},
			/**
			 * 地址开始
			 */
			handleAddress() { //地址弹窗打开/关闭
				this.isAddress = !this.isAddress
				if (this.isAddress) {
					this.getAddressAction(this.formAddress)
				}
			},
			// 用户可用优惠券查询
			async getSalesCouponAction() {
				var res = await getSalesCouponAction(this.fixedCS);

				if (res.tableData.length > 0) {
					this.coupon = res.tableData;
					this.coupon.forEach(item => {
						item.checked = "circle";
					})
					var arr = {};
					for (var i = 0; i < this.coupon.length; i++) {
						for (var j = i + 1; j < this.coupon.length - 1; j++) {
							if (this.coupon[i].Preferential > this.coupon[j].Preferential) {
								arr = {
									...this.coupon[i].Preferential
								}
								this.coupon[i] = {
									...this.coupon[j]
								}
								this.coupon[j] = {
									arr
								}
							}
						}
					}

				}
			},
			async getAddressAction(data, onReach = false) { //查询地址
				if (!this.loading) {
					this.loading = true;
					uni.showLoading({
						title: "加载中...",
					});
					const res = await getAddressAllAction(data);
					if (res.Status == 'success') {
						//判断是否重新开始查询
						if (!onReach) {
							this.formAddress.page = 1
							this.tableDataAddress = [];
						}
						res.tableData.forEach((item, index) => {
							this.tableDataAddress.push(item);
						})
						this.totalAddress = Number(res.limit);
					}
					uni.hideLoading();
					this.loading = false;
				}
			},
			onAddressScollBottom() { //地址滚动到底部
				if (this.isReachAddress) {
					if (this.tableDataAddress.length < this.totalAddress) {
						this.formAddress.page++;
						this.getAddressAction(this.formAddress, true)
					} else {
						this.isReachAddress = false;
					}
				}
			},
			selectAddress(item) { //选择地址
				this.customerAddress = item
				console.log(this.customerAddress, '信息');
				this.isAddress = false
				this.tableDataAddress = [];
				this.formAddress.page = 1
			},
			handleAddressAdd() { //地址跳转添加
				uni.navigateTo({
					url: '/pages/delivery/addressAdd'
				})
			},
			handleAddressEdit(Address_SerialNumber) { //地址跳转添加
				uni.navigateTo({
					url: '/pages/delivery/addressEdit?Address_SerialNumber=' + Address_SerialNumber
				})
			},
			/**
			 * 提货人
			 */
			handlePickupPerson() { //提货人弹窗打开/关闭
				this.isPickupPerson = !this.isPickupPerson
				if (this.isPickupPerson) {
					this.getPickupPerson(this.formPickup);
				}
			},
			async getPickupPerson(data, onReach = false) {
				if (!this.loading) {
					this.loading = true;
					uni.showLoading({
						title: "加载中...",
					});
					const res = await getPickerAllAction(data);
					if (res.Status == 'success') {
						//判断是否重新开始查询
						if (!onReach) {
							this.formPickup.page = 1
							this.tableDataPickup = [];
						}
						this.tableDataPickup.push(...res.tableData);
						this.totalPickup = Number(res.limit);
					}
					uni.hideLoading();
					this.loading = false;
				}
			},
			onPickupScollBottom() { //到底刷新数据
				if (this.isReachPickup) { //是否有剩余数据
					if (this.tableDataAddress.length < this.totalPickup) {
						this.formPickup.page++;
						this.getPickerAllAction(this.formPickup, true)
					} else {
						this.isReachPickup = false;
					}
				}
			},
			pickupPersonAdd() { //添加
				uni.navigateTo({
					url: "/pages/delivery/pickupPersonAdd"
				})
			},
			pickupPersonEdit(Picker_SerialNumber) { //修改
				uni.navigateTo({
					url: "/pages/delivery/pickupPersonEdit?Picker_SerialNumber=" +
						Picker_SerialNumber
				})
			},
			selectpickupPerson(item) { //选择
				this.defaultPerson = item
				this.isPickupPerson = false
				this.tableDataPickup = [];
				this.formPickup.page = 1
			},
			/**
			 * 
			 */
			handleDelivery() { //配送弹窗打开/关闭
				this.isDelivery = !this.isDelivery
			},
			handleCoupon() { //优惠券弹窗打开/关闭
				this.isCoupon = !this.isCoupon
			},
			PickerChange(e) { //储值卡选择器
				this.prepayment_card = this.card[e.detail.value]
			},
			async handlePay(item) { //选中支付方式
				this.pay.forEach(item => {
					item.isSelect = false
				})
				item.isSelect = true;
				this.selectedPay = item.Name;
				if (this.selectedPay == '储值支付' && this.first) {
					this.first = false;
					const res = await getprepaymentCardSalesAction({
						Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
						Open_ID: app.globalData.Open_ID,
						Article_SerialNumber: this.fixedCS.Article_SerialNumber
					})
					if (res.Status == 'success') {
						this.card = res.Data
						this.card.forEach(item => {
							item.Name = item.Prepayment_Card_Scheme_Name + '(剩余金额：' + accAdd(item
								.Prepayment_Balance, item.Gift_Balance) + '元)'
							item.Amount = accAdd(item.Prepayment_Balance, item.Gift_Balance)
						})
						return
					}
					this.first = true;
				}
			},
			// async wxPayfor() { //提交订单
			// 	const _this = this
			// 	if (!this.loading) {
			// 		if (!this.customerAddress) {
			// 			uni.showToast({
			// 				title: "您还未选择地址！",
			// 				icon: "error",
			// 			});
			// 		} else {
			// 			if (this.goods.length > 0) {
			// 				this.loading = true
			// 				uni.showLoading({
			// 					title: "加载中...",
			// 				});
			// 				var sales_arr = [];
			// 				var Check = [];
			// 				let GoodsPrice = 0; // 商品总价格
			// 				let GiftsGoodsPrice = 0; // 赠品总价
			// 				let allGoodPrice = 0; // 商品总价不算赠品
			// 				console.log(this.goods, '123');
			// 				this.goods.forEach(item => {
			// 					GoodsPrice = _this.AccAdd(GoodsPrice, item.Amount);
			// 					let sales_order = {}
			// 					// var Coupon_Unit_Price = accSub(item.Amount, item.jm).toFixed(2) //减免后的价格
			// 					sales_order.Sales_Order_SerialNumber = item.Sales_Order_SerialNumber
			// 					sales_order.Sales_Date = item.Sales_Date
			// 					sales_order.Sales_Unit_Price = item.Sales_Unit_Price
			// 					sales_order.Amount = item.Amount
			// 					sales_order.Order_Type = 0
			// 					sales_order.Sales_Unit_Price_Stock_SerialNumber = item
			// 						.Sales_Unit_Price_Stock_SerialNumber
			// 					sales_order.Quantity = item.Quantity
			// 					sales_order.Sales_Address = _this.customerAddress.Address + _this
			// 						.customerAddress.Address_Details
			// 					sales_order.Sales_Contacts = _this.customerAddress.Name
			// 					sales_order.Sales_Phone = _this.customerAddress.Phone
			// 					sales_order.Sales_Message = _this.message
			// 					sales_order.Coupon_Unit_Price = item.jm
			// 					sales_order.Enterprise_Info_SerialNumber = app.globalData
			// 						.Enterprise_Info_SerialNumber
			// 					sales_arr.push(sales_order)
			// 					const checkobj = {}
			// 					checkobj.Sales_Unit_Price_Stock_SerialNumber = item
			// 						.Sales_Unit_Price_Stock_SerialNumber
			// 					checkobj.Quantity = item.Quantity
			// 					Check.push(checkobj)
			// 					// 赠品添加
			// 					if (item.Children.Gifts.length > 0) {
			// 						item.Children.Gifts.forEach((item1, index) => {
			// 							allGoodPrice = _this.AccAdd(allGoodPrice, item1.Amount);
			// 							let sales_order = {}
			// 							// var Coupon_Unit_Price = accSub(item.Amount, item.jm).toFixed(2) //减免后的价格
			// 							sales_order.Sales_Order_SerialNumber = item
			// 								.Sales_Order_SerialNumber
			// 							sales_order.Article_SerialNumber = item1.Article_SerialNumber
			// 							sales_order.Article_Specifications_SerialNumber = item1
			// 								.Article_Specifications_SerialNumber
			// 							sales_order.Sales_Date = item.Sales_Date
			// 							sales_order.Sales_Unit_Price = item1.Sales_Unit_Price
			// 							sales_order.Amount = item1.Amount
			// 							sales_order.Sign = item1.Sign
			// 							sales_order.Order_Type = 1
			// 							sales_order.Sales_Unit_Price_Stock_SerialNumber = item1
			// 								.Sales_Unit_Price_Stock_SerialNumber
			// 							sales_order.Quantity = item1.Quantity
			// 							sales_order.Sales_Address = _this.customerAddress.Address +
			// 								_this
			// 								.customerAddress.Address_Details
			// 							sales_order.Sales_Contacts = _this.customerAddress.Name
			// 							sales_order.Sales_Phone = _this.customerAddress.Phone
			// 							sales_order.Sales_Message = _this.message
			// 							// sales_order.Coupon_Unit_Price = item.jm
			// 							sales_order.Enterprise_Info_SerialNumber = app.globalData
			// 								.Enterprise_Info_SerialNumber
			// 							sales_arr.push(sales_order)
			// 							const checkobj = {}
			// 							checkobj.Sales_Unit_Price_Stock_SerialNumber = item1
			// 								.Sales_Unit_Price_Stock_SerialNumber
			// 							checkobj.Quantity = item1.Quantity
			// 							Check.push(checkobj)
			// 						})
			// 					}
			// 				})
			// 				allGoodPrice = _this.AccAdd(GoodsPrice, GiftsGoodsPrice);
			// 				console.log(sales_arr, '看看', Check);
			// 				const res = await addWeChatsetSalesOrderAction({
			// 					Data: JSON.stringify(sales_arr),
			// 					Check: JSON.stringify(Check),
			// 					Open_ID: app.globalData.Open_ID,
			// 					Type: 2
			// 				})
			// 				console.log(allGoodPrice, '价格', '单号', res);
			// 				if (res.Status == 'success') {
			// 					this.Pay(res.Data, allGoodPrice)
			// 				}
			// 			} else {
			// 				uni.showToast({
			// 					title: '您还未选择商品!',
			// 					icon: 'error',
			// 				})
			// 			}
			// 		}
			// 	}
			// },
			async wxPayfor() { //提交订单
				const _this = this
				if (this.customerAddress != null) {
					if (!this.loading) {
						this.loading = true
						uni.showLoading({
							title: "加载中...",
						});
						let time = new Date().getTime()
						let sales_order = {
							Sales_Order_SerialNumber: app.globalData.Open_ID + '_' + time,
							Store_SerialNumber: this.Store_SerialNumber,
							Sales_Address: this.customerAddress.Address + this.customerAddress.Address_Details,
							Sales_Contacts: this.customerAddress.Name,
							Sales_Phone: this.customerAddress.Phone,
							Sales_Message: this.Sales_Message,
							Sales_Date: NowTime(),
							Open_ID: app.globalData.Open_ID,
							App_ID: app.globalData.App_ID,
							Sales_Amount: this.totalPrice,
							Collection_Amount: 0,
							Delivery_Amount: 0,
							Receive_Type: 0,
							Refund_Type: 0,
							Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
							Children: {
								sales_order_detail: []
							},
						}
						if (this.postcardRule == 0) {
							this.goods.forEach((item, index) => {
								sales_order.Children.sales_order_detail.push({
									Sales_Order_Detail_SerialNumber: app.globalData.Open_ID + '_' +
										time + '_' + addZero(index + 1, 3),
									Sales_Order_SerialNumber: app.globalData.Open_ID + '_' + time,
									Sales_Unit_Price_Stock_SerialNumber: item
										.Sales_Unit_Price_Stock_SerialNumber,
									Sales_Unit_Price_Detail_SerialNumber: item.Execute_Unit_Price_SerialNumber?item.Execute_Unit_Price_SerialNumber:'',
									Article_SerialNumber: item.Article_SerialNumber,
									Article_Name: item.Article_Name,
									Article_Specifications_SerialNumber: item
										.Article_Specifications_SerialNumber,
									Sign: item.Sign,
									Quantity: item.Quantity,
									Unit_Price: item.Unit_Price,
									Sales_Unit_Price: item.Sales_Unit_Price,
									Amount: item.Amount,
									Receive_Type: 0,
									Refund_Type: 0,
									Order_Type: 0,
									Enterprise_Info_SerialNumber: app.globalData
										.Enterprise_Info_SerialNumber,
								})
							})
						} else {
							sales_order.Store_SerialNumber = this.selectGoods[0].Store_SerialNumber
							this.selectGoods.forEach((item, index) => {
								sales_order.Children.sales_order_detail.push({
									Sales_Order_Detail_SerialNumber: app.globalData.Open_ID + '_' +
										time + +'_' + addZero(index + 1, 3),
									Sales_Order_SerialNumber: app.globalData.Open_ID + '_' + time,

									Sales_Unit_Price_Stock_SerialNumber: item.Sales_Unit_Price_Stock_SerialNumber,
									Sales_Unit_Price_Detail_SerialNumber: item.Execute_Unit_Price_SerialNumber?item.Execute_Unit_Price_SerialNumber:'',
									Article_SerialNumber: item.Article_SerialNumber,
									Article_Name: item.Article_Name,
									Article_Specifications_SerialNumber: item
										.Article_Specifications_SerialNumber,
									Sign: item.Sign,
									Quantity: item.Quantity,
									Unit_Price: item.Unit_Price,
									Sales_Unit_Price: item.Sales_Unit_Price,
									Amount: item.Amount,
									Receive_Type: 0,
									Refund_Type: 0,
									Order_Type: 0,
									Enterprise_Info_SerialNumber: app.globalData
										.Enterprise_Info_SerialNumber,
								})
							})
						}
						// if(index==0){
						// 	item.Sales_Order_Detail_SerialNumber = 'H01000000010610'
						// }else{
						// 	item.Sales_Order_Detail_SerialNumber = 'H01000000010612'

						// }
						if(this.Collection_SerialNumber==''){
							console.log({
								Data:{
									sales_order: [sales_order]
								},
								OperationType:1
							});
							const res = await salesOrderSaveAction({
								Data: JSON.stringify({
									sales_order: [sales_order]
								}),
								OperationType:1
							})
							if (res.Status == 'success') {
								this.Pay(res.Data)
							}else if(res.Status == "Fail"){
								uni.hideLoading();
								uni.showToast({
									title: '库存不足！',
									icon: 'error'
								})
							}
							console.log(res);
						}else{
							this.postcardStatus = true
						}
						
						// if (this.Collection_SerialNumber == '') {
						// 	this.WebSocket(async () => {
						// 		await setAsynChronousAdd({
						// 			Data: JSON.stringify({
						// 				sales_order: [sales_order]
						// 			}),
						// 			OperationType: 1,
						// 			Open_ID: app.globalData.Open_ID,
						// 			Name: 'submitSalesOrder' + app.globalData.Open_ID
						// 		})
						// 	})
						// } else {
						// 	this.postcardStatus = true
						// }
						this.loading = false;
						uni.hideLoading();
					}
				} else {
					uni.showToast({
						title: '您还未选择地址！',
						icon: 'error'
					})
				}
			},
			WebSocket(callback) {
				this.websocket = new WebSocketIO('submitSalesOrder' + app.globalData.Open_ID, this.$websocketUrl, 10000)
				this.websocket.connectSocketInit();
				uni.$on("socketMsg", (res) => {
					res = JSON.parse(res)
					this.websocket.closeSocket();
					if (res.Status == "success") {
						console.log(res.Data);
						this.Pay(res.Data)
					} else if (res.Status == "Fail") {
						uni.hideLoading();
						this.loading = false;
						uni.showToast({
							title: '库存不足！',
							icon: 'error'
						})
					}
				})
				callback();
			},
			showPassword() {
				this.passwordStatus = !this.passwordStatus
				if (this.passwordStatus) {
					this.passwordIcon = 'eye'
				} else {
					this.passwordIcon = 'eye-slash'
				}
			},
			async exchange() {
				this.loading = true;
				// 待修改
				if (this.postcardPassword != '') {
					uni.showLoading({
						title: '正在领取中....',
						icon: 'loading',
					})
					const res = await CollectionEdit({
						Collection_SerialNumber: this.Collection_SerialNumber,
						Password: this.postcardPassword,
						type: '3',
						Open_ID: app.globalData.Open_ID,
					})
					uni.hideLoading();
					if (res.Status == 'success') {
						uni.showToast({
							title: '领取成功!',
							duration: 1000
						})
						uni.navigateTo({
							url: "/pages/index/index"
						})
					} else {
						uni.showToast({
							title: res.Cause,
							icon: 'error',
							duration: 1000
						})
					}
					// 接口返回值正确

					this.postcardStatus = false;
					this.loading = false;
				} else {
					uni.showToast({
						title: '礼品卡密码不能为空!',
						icon: 'error',
						duration: 1000
					})
					this.loading = false;
				}
			},
			async Pay(Sales_Order_SerialNumber) {
				// console.log(Sales_Order_SerialNumber, allGoodPrice);
				uni.showLoading({
					title: "提交订单...",
				});
				let Collection_Type = '礼品卡兑换'
				const res = await WeChatDefray({
					Sales_Order_SerialNumber,
					Collection_Type,
					Open_ID: app.globalData.Open_ID,
					Data: JSON.stringify({
						Gift_Card_SerialNumber: this.Gift_Card_SerialNumber
					})
				})
				console.log(res);
				this.loading = false
				uni.hideLoading();
				if (res.Status == "success") {
					this.Collection_SerialNumber = res.Data
					this.postcardStatus = true
				} else {
					uni.showToast({
						title: '提交失败，请重试！',
						icon: 'error'
					})
				}

			}
		}
	}
</script>

<style lang="scss" scoped>
	.zfAlert {
		position: fixed;
		top: 0;
		left: 0;
		bottom: 0;
		right: 0;
		margin: auto;
		z-index: 10000;
		background-color: #00000099;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.code {
		>view {
			border: 1px solid #DDDDDD;
			border-radius: 8rpx;
			overflow: hidden;

			view {
				display: flex;
				align-items: center;
				justify-content: center;
				width: 100rpx;
				height: 100rpx;
				background: #FAFAFA;
				font-size: 60rpx;

				&:not(:last-child) {
					border-right: 1px solid #DDDDDD;
				}
			}
		}
	}

	.keyboard {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background: #EEEEEE;

		button {
			display: flex;
			align-items: center;
			justify-content: center;
			width: calc(100vw / 3 - 1px);
			background: #FFFFFF;
			border-radius: 0;
			margin-top: 1px;
			font-size: 50rpx;
			height: 120rpx;

			&.button-hover:not(.hide) {
				background: #EEEEEE;
			}

			image {
				width: 52rpx;
				height: 38rpx;
			}
		}
	}
</style>